var fs = require("fs");
var _ = require("lodash");

let fileNameC = "Character";
let fileName1 = "./data/skill4";
let fileName2 = "ChaPaDes";
let fileName3 = "chaDes";
let fileName4 = "Client_Talent";
let outputFileName = "./data/character3.json";

let mainData = JSON.parse(fs.readFileSync(`${fileNameC}.json`).toString()).map;
let skill2 = JSON.parse(fs.readFileSync(`${fileName1}.json`).toString());
let chaPa = JSON.parse(fs.readFileSync(`${fileName2}.json`).toString()).map;
let chaDes = JSON.parse(fs.readFileSync(`${fileName3}.json`).toString()).map;
let talent = JSON.parse(fs.readFileSync(`${fileName4}.json`).toString()).map;

let skillMap = new Map();
let chaPaMap = new Map();
let chaDesMap = new Map();
let talentMap = new Map();
_.forEach(skill2, (e) => {
  let id = e.id;
  let data = e.data;
  skillMap.set(id, data);
});
_.forEach(chaPa, (e) => {
  let id = e.id;
  let data = e.data;
  chaPaMap.set(id, data);
});
_.forEach(chaDes, (e) => {
  let id = e.id;
  let data = e.data;
  chaDesMap.set(id, data);
});
_.forEach(talent, (e) => {
  let id = e.id;
  let data = e.data;
  talentMap.set(id, data);
});
_.forEach(mainData, (e) => {
  _.forEach(e.data.characterTalent, (obj) => {
    if (talentMap.has(obj.talent)) {
      _.assign(obj, talentMap.get(obj.talent));
    }
  });
  _.forEach(e.data.chaLB, (x) => {
    if (skillMap.has(x.id)) {
      _.assign(x, skillMap.get(x.id));
    }
  });
  let finalId = e.data.chaLB[e.data.chaLB.length - 1].id + 1;
  if (skillMap.has(finalId)) {
    e.data.chaLB.push(skillMap.get(finalId));
  }
  _.forEach(e.data.chaSkills, (obj) => {
    _.forEach(obj.chaSkill, (x) => {
      if (skillMap.has(x.id)) {
        _.assign(x, skillMap.get(x.id));
      }
    })
    let finalId = obj.chaSkill[obj.chaSkill.length - 1].id + 1;
    if (skillMap.has(finalId)) {
      obj.chaSkill.push(skillMap.get(finalId));
    }
  });
  _.forEach(e.data.chaPas, (obj) => {
    _.forEach(obj.chaPaskill_, (x) => {
      if (chaPaMap.has(x.id)) {
        _.assign(x, chaPaMap.get(x.id));
      }
      let finalId = obj.chaPaskill_[obj.chaPaskill_.length - 1].id + 1;
      if (chaPaMap.has(finalId)) {
        obj.chaPaskill_.push(chaPaMap.get(finalId));
      }
    })
  });
  if (e.data.spChaPas) {
    _.forEach(e.data.spChaPas.spChaPaskill, (x) => {
      if (chaPaMap.has(x.id)) {
        _.assign(x, chaPaMap.get(x.id));
      }
    })
  }
  let id = e.data.id;
  if (chaDesMap.has(id)) {
    _.assign(e.data, chaDesMap.get(id));
  }
});

fs.writeFileSync(outputFileName, JSON.stringify(mainData));
